<template>
    <div class="member-info-page">
        <UserSteps :currentStep="2" />

        <!-- 注意事项 -->
        <div class="notice-section">
            <p><strong>注意事项如下：</strong></p>
            <p>① 本次诊断面向企业全员，请准确录入员工名单；</p>
            <p>② 部门：根据公司组织架构选择；</p>
            <p>③ 姓名：请填写完整真实姓名，否则无法正确录入系统；</p>
            <p>④ 层级关系：4个层级包括“高层、中层、基层、一线”
            </p>
            <p> 绩效评价（非必填）：只要按【优秀、及格、不及格】由高到低三个层次排名，如未考核者由主管依表现评级。
            </p>
        </div>
        <!-- 表单录入区域 -->
        <div class="form-section">
            <van-form @submit="onSubmit" class="member-form">
                <van-cell-group inset>
                    <van-field v-model="formData.department" name="department" label="部门" placeholder="请选择部门"
                        :rules="[{ required: true, message: '请选择部门' }]" label-align="left" is-link readonly
                        @click="showDepartmentPicker = true" />

                    <van-field v-model="formData.name" name="name" label="姓名" placeholder="请输入姓名"
                        :rules="[{ required: true, message: '请输入姓名' }]" label-align="left" />

                    <van-field v-model="formData.position" name="position" label="岗位名称" placeholder="请输入岗位名称"
                        :rules="[{ required: true, message: '请输入岗位名称' }]" label-align="left" />

                    <!-- 层级关系下拉框 -->
                    <van-field v-model="formData.level" name="level" label="层级关系" placeholder="请选择层级关系"
                        :rules="[{ required: true, message: '请选择层级关系' }]" label-align="left" is-link readonly
                        @click="showLevelPicker = true" />
                    <van-popup v-model:show="showLevelPicker" position="bottom">
                        <van-picker :columns="levelColumns" @confirm="onLevelConfirm"
                            @cancel="showLevelPicker = false" />
                    </van-popup>

                    <!-- 绩效评价下拉框 -->
                    <van-field v-model="formData.performance" name="performance" label="绩效评价" placeholder="请选择绩效评价"
                        label-align="left" is-link readonly @click="showPerformancePicker = true" />
                    <van-popup v-model:show="showPerformancePicker" position="bottom">
                        <van-picker :columns="performanceColumns" @confirm="onPerformanceConfirm"
                            @cancel="showPerformancePicker = false" />
                    </van-popup>
                </van-cell-group>

                <div class="form-actions">
                    <van-button round block type="primary" native-type="submit">
                        添加人员
                    </van-button>
                </div>
            </van-form>
        </div>

        <!-- 自动生成的表格 -->
        <div class="table-section">
            <div class="table-title">测评人员名单</div>
            <div class="member-table">
                <table>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th style="width: 17%;">部门</th>
                            <th style="width: 17%;">姓名</th>
                            <th style="width: 17%;">岗位</th>
                            <th>层级</th>
                            <th>绩效评价</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 示例数据 -->
                        <tr class="example-row">
                            <td>例</td>
                            <td>市场部</td>
                            <td>张三</td>
                            <td>销售经理</td>
                            <td>中层</td>
                            <td>优秀</td>
                        </tr>

                        <!-- 动态生成的数据 -->
                        <tr v-for="(item, index) in memberList" :key="index" @click.stop="handleRowClick(item, index)"
                            class="data-row">
                            <td>{{ index + 1 }}</td>
                            <!-- 修改表格中的部门显示 -->
                            <td>
                                <van-popover v-model:show="popoverStates[`${item.department}_${index}`]"
                                    :actions="getDepartmentActions(item.department, index)" theme="dark"
                                    placement="top">
                                    <template #reference>
                                        <span @click.stop="clickDepartment(item.department, index)">
                                            {{ item.department.split('/').pop() }}
                                        </span>
                                    </template>
                                </van-popover>
                            </td>
                            <td>{{ item.name }}</td>
                            <td>{{ item.position }}</td>
                            <td>{{ item.level }}</td>
                            <td>{{ item.performance }}</td>
                        </tr>
                    </tbody>
                </table>
                <!-- 添加保存成员信息按钮 -->
                <div v-if="memberList.length > 0" class="save-actions"
                    style="width: 85vw; margin: 20px auto 0;margin-bottom: 15px;">
                    <van-button round block type="primary" @click="saveMemberInfo()">
                        保存测评人员名单
                    </van-button>
                </div>
                <div v-if="memberList.length > 0" class="save-actions"
                    style="width: 85vw; margin: 20px auto 0;margin-bottom: 15px;">
                    <van-button round block type="primary" @click="showEditPopup = true;">
                        修改测评人员信息
                    </van-button>
                </div>
            </div>
        </div>
    </div>
    <!-- 编辑弹窗 -->
    <van-popup v-model:show="showEditPopup" position="bottom" round style="height: 80%">
        <div class="edit-popup">
            <div class="popup-header">
                <div>
                    <span class="cancel-btn" @click="showEditPopup = false">取消</span>
                </div>
                <div class="title" style="margin-left: 15px;">编辑人员信息</div>
                <div>
                    <span class="delete-btn" @click="deleteRow(editFormData.index)">删除</span>

                    <span class="confirm-btn" @click="saveEdit">保存</span>
                </div>

            </div>

            <div class="edit-form">
                <van-cell-group inset>
                    <van-field v-model="editFormData.department" label="部门" placeholder="请选择部门"
                        :rules="[{ required: true, message: '请选择部门' }]" label-align="left" is-link readonly
                        @click="showEditDepartmentPicker = true" />


                    <van-field v-model="editFormData.name" label="姓名" placeholder="请输入姓名"
                        :rules="[{ required: true, message: '请输入姓名' }]" label-align="left" />

                    <van-field v-model="editFormData.position" label="岗位名称" placeholder="请输入岗位名称"
                        :rules="[{ required: true, message: '请输入岗位名称' }]" label-align="left" />

                    <!-- 层级关系下拉框 -->
                    <van-field v-model="editFormData.level" label="层级关系" placeholder="请选择层级关系"
                        :rules="[{ required: true, message: '请选择层级关系' }]" label-align="left" is-link readonly
                        @click="() => { showEditLevelPicker = true }" />

                    <van-popup v-model:show="showEditLevelPicker" position="bottom">
                        <van-picker :columns="levelColumns" @confirm="onEditLevelConfirm"
                            @cancel="showEditLevelPicker = false" />
                    </van-popup>

                    <!-- 绩效评价下拉框 -->
                    <van-field v-model="editFormData.performance" label="绩效评价" placeholder="请选择绩效评价" label-align="left"
                        is-link readonly @click="() => { showEditPerformancePicker = true }" />

                    <van-popup v-model:show="showEditPerformancePicker" position="bottom">
                        <van-picker :columns="performanceColumns" @confirm="onEditPerformanceConfirm"
                            @cancel="showEditPerformancePicker = false" />
                    </van-popup>
                </van-cell-group>
            </div>
        </div>

    </van-popup>
    <van-popup v-model:show="showDepartmentPicker" position="bottom">
        <van-picker title="部门选择" :columns="levelList" :columns-field-names="customFieldName"
            @confirm="onDepartmentConfirm" @cancel="showDepartmentPicker = false" />
    </van-popup>
    <van-popup v-model:show="showEditDepartmentPicker" position="bottom">
        <van-picker title="部门选择" :columns="levelList" :columns-field-names="customFieldName"
            @confirm="onEditDepartmentConfirm" @cancel="showEditDepartmentPicker = false" />
    </van-popup>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { showToast } from 'vant'
import { getEnterpriseById, updateEnterprise } from '../api/enterprise'
import UserSteps from '../components/UserSteps.vue'
/**
 * 表单部分
 */
// 表单数据
const formData = reactive({
    department: '',
    name: '',
    position: '',
    level: '',
    performance: ''
})
//静态企业信息
const enterpriseInfo = ref<any>({})
//层级列表
const levelList = ref<any[]>([])


// 成员列表
const memberList = ref<any[]>([

])
// 部门级联选择器相关
const showDepartmentPicker = ref(false)         //表单
const showEditDepartmentPicker = ref(false)     //编辑弹窗

// 提交表单处理
const onSubmit = () => {
    // 验证必填字段
    if (!formData.department) {
        showToast('请选择部门')
        return
    }
    if (!formData.name) {
        showToast('请输入姓名')
        return
    }
    if (!formData.position) {
        showToast('请输入岗位名称')
        return
    }
    if (!formData.level) {
        showToast('请选择层级关系')
        return
    }

    // 添加新成员到列表
    memberList.value.push({
        department: formData.department,
        name: formData.name,
        position: formData.position,
        level: formData.level,
        performance: formData.performance
    })

    // 重置表单
    formData.department = ''
    formData.name = ''
    formData.position = ''
    formData.level = ''
    formData.performance = ''

    showToast('人员添加成功')
}

// 添加层级关系和绩效评价的选择器显示控制
const showLevelPicker = ref(false)
const showPerformancePicker = ref(false)

// 层级关系选项
const levelColumns = ref([
    { text: '高层', value: '高层' },
    { text: '中层', value: '中层' },
    { text: '基层', value: '基层' },
    { text: '一线', value: '一线' }
])

// 绩效评价选项
const performanceColumns = ref([
    { text: '优秀', value: '优秀' },
    { text: '及格', value: '及格' },
    { text: '不及格', value: '不及格' }
])

// 层级关系确认回调
const onLevelConfirm = ({ selectedOptions }: { selectedOptions: any[] }) => {
    formData.level = selectedOptions[0].value
    showLevelPicker.value = false
}

// 绩效评价确认回调
const onPerformanceConfirm = ({ selectedOptions }: { selectedOptions: any[] }) => {
    formData.performance = selectedOptions[0].value
    showPerformancePicker.value = false
}



/*表格部分*/
// 修改数据声明
const popoverStates = ref<Record<string, boolean>>({})
const departmentActions = ref<Record<string, Array<{ text: string, value: number }>>>({})
// 修改clickDepartment方法
const clickDepartment = (departmentPath: string, index: number) => {
    const key = `${departmentPath}_${index}`;
    // 确保该部门的状态存在
    if (popoverStates.value[key] === undefined) {
        popoverStates.value[key] = false;
    }

    // 设置当前部门的完整路径作为action
    departmentActions.value[key] = [{ text: departmentPath, value: 1 }];

    // 切换popover显示状态
    popoverStates.value[key] = !popoverStates.value[key];
}

// 修改获取actions的方法
const getDepartmentActions = (departmentPath: string, index: number) => {
    const key = `${departmentPath}_${index}`;
    return departmentActions.value[key] || [{ text: departmentPath, value: 1 }];
}
// 在表格行点击事件中阻止popover触发
const handleRowClick = (rowData: any, index: number, event?: Event) => {
    event?.stopPropagation();
    editRow(rowData, index);
}

// 编辑数据弹窗
// 添加编辑和删除相关的状态
const showEditPopup = ref(false)
const editFormData = reactive({
    index: -1,
    department: '',
    name: '',
    position: '',
    level: '',
    performance: ''
})
// 为编辑弹窗添加独立的选择器控制
const showEditLevelPicker = ref(false)
const showEditPerformancePicker = ref(false)
// 编辑行数据
const editRow = (item: any, index: number) => {
    editFormData.index = index
    editFormData.department = item.department
    editFormData.name = item.name
    editFormData.position = item.position
    editFormData.level = item.level
    editFormData.performance = item.performance
    // showEditPopup.value = true
}

// 删除行数据
const deleteRow = (index: number) => {
    memberList.value.splice(index, 1)
    showEditPopup.value = false
    showToast('删除成功')
}

// 保存编辑的数据
const saveEdit = () => {
    if (editFormData.index >= 0) {
        memberList.value[editFormData.index] = {
            department: editFormData.department,
            name: editFormData.name,
            position: editFormData.position,
            level: editFormData.level,
            performance: editFormData.performance
        }
        showToast('修改成功')
    }
    showEditPopup.value = false
}

// 编辑弹窗中的层级关系确认回调
const onEditLevelConfirm = ({ selectedOptions }: { selectedOptions: any[] }) => {
    editFormData.level = selectedOptions[0].value
    showEditLevelPicker.value = false
}

// 编辑弹窗中的绩效评价确认回调
const onEditPerformanceConfirm = ({ selectedOptions }: { selectedOptions: any[] }) => {
    editFormData.performance = selectedOptions[0].value
    showEditPerformancePicker.value = false
}

// 编辑弹窗中的部门选择确认回调
const onEditDepartmentConfirm = ({ selectedOptions }: { selectedOptions: any[] }) => {
    // 过滤掉"请选择"选项，只拼接有效的部门名称
    const validOptions = selectedOptions.filter(option => option.name !== '无下级部门');
    editFormData.department = validOptions.map(option => option.name).join('/');
    showEditDepartmentPicker.value = false;
}

/*层级部门选择部分*/
// 定义树形结构的接口
interface TreeNode {
    id: number;
    name: string;
    value?: string;
    children?: TreeNode[];
}

const customFieldName = {
    text: 'name',
    value: 'value',
    children: 'children',
};
// 层级部门选择确认回调
const onDepartmentConfirm = ({ selectedOptions }: { selectedOptions: any[] }) => {
    // 构建完整的部门路径
    // 过滤掉"请选择"选项，只拼接有效的部门名称
    const validOptions = selectedOptions.filter(option => option.name !== '无下级部门');
    formData.department = validOptions.map(option => option.name).join('/');
    showDepartmentPicker.value = false;
}

//将数据转换为树形结构
const handleLeveList = (list: any[]): TreeNode[] => {
    return list.map((item) => {
        const node: TreeNode = {
            id: item.id,
            name: item.name,
            value: item.name
        };

        // 如果有子节点，则添加空占位节点在前面
        if (item.childrenNodes && item.childrenNodes.length > 0) {
            // 先添加一个空的占位节点
            const placeholderNode: TreeNode = {
                id: 0,
                name: '无下级部门',
                value: '',
            };

            // 然后处理实际的子节点
            const actualChildren = handleLeveList(item.childrenNodes);

            // 将占位节点和实际子节点组合
            node.children = [placeholderNode, ...actualChildren];
        }

        return node;
    });
};
//保存层级部门选择数据
const saveMemberInfo = () => {
    enterpriseInfo.value.currentMenber = JSON.stringify(memberList.value)
    updateEnterprise(enterpriseInfo.value).then((res: any) => {
        if (res.code === 200) {
            showToast('保存成功')
        }
    }).catch((error) => {
        console.error('保存层级部门数据失败:', error)
        showToast('保存层级部门数据失败')
    });
    console.log("保存层级部门数据 ", enterpriseInfo.value)
}


//组件挂载时获取企业信息
onMounted(async () => {
    //获取企业信息
    const user = JSON.parse(localStorage.getItem('user')!)
    enterpriseInfo.value = await getEnterpriseById(user.enterpriseId).then((res: any) => {
        if (res.code === 200) {

            levelList.value = handleLeveList(JSON.parse(res.data.orgJson))
            console.log(JSON.parse(res.data.orgJson))
            console.log(levelList.value)
            return res.data
        }
    })
        .catch((error) => {
            console.error('获取企业信息失败:', error)
            // 可以在这里添加错误提示或其他处理逻辑
            showToast('获取企业信息失败')
        })
    if (enterpriseInfo.value.currentMenber != null) {
        memberList.value = JSON.parse(enterpriseInfo.value.currentMenber)
    }
})


</script>

<style scoped>
.member-info-page {
    padding: 10px;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    font-size: 16px;
}

.notice-section {
    background-color: #f5f5f5;
    border: 1px solid #ddd;
    padding: 15px;
    margin-bottom: 20px;
    text-align: left;
    font-size: 14px;
    line-height: 1.5;
}

.form-section {
    margin-bottom: 20px;
}

.table-section {
    flex: 1;
    margin-bottom: 20px;
}

.table-title {
    text-align: center;
    font-weight: bold;
    background-color: #e0e0e0;
    padding: 10px;
    margin-bottom: 10px;
    font-size: 16px;
}

.member-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
    /* 为底部导航栏预留空间 */

    padding-bottom: 70px;
}

.member-table table {
    width: 100%;
    border-collapse: collapse;
}

.member-table th,
.member-table td {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: center;
    width: 15%;
    /* 固定列宽 */
    font-size: 14px;
    /* 字体变小 */
}

.member-table th {
    background-color: #008080;
    color: white;
    font-weight: bold;
    font-size: 16px;

}

.example-row {
    background-color: #ffff00;
}

.member-form {
    flex: 1;
}

.form-actions {
    margin-top: 20px;
    padding: 0 15px;
}

.data-row {
    cursor: pointer;
}

.data-row:hover {
    background-color: #f0f0f0;
}

.edit-popup {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #eee;
}

.popup-header .title {
    font-size: 16px;
    font-weight: bold;
}

.popup-header .cancel-btn,
.popup-header .confirm-btn {
    font-size: 14px;
    color: #1989fa;
    padding: 5px 10px;
}

.popup-header .delete-btn {
    font-size: 14px;
    color: #f74e62;
    padding: 5px 10px;
}


.edit-form {
    flex: 1;
    overflow-y: auto;
    padding: 10px 0;
}


:deep(.van-cell-group--inset) {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-top: 10px;
}

:deep(.van-cell__title) {
    font-size: 16px;
    font-weight: 500;
}
</style>